home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
C/C++ Users Group Library 1996 July
/
C-C++ Users Group Library July 1996.iso
/
listings
/
v_09_03
/
9n03084a
< prev
next >
Wrap
Text File
|
1991-01-15
|
2KB
|
85 lines
/*-----------------------------------
* This program was used to test the
* add1 and add2 functions
*-----------------------------------*/
#include <stdio.h>
typedef struct NODE* LINK;
struct NODE {
int info;
LINK left;
LINK right;
};
main()
{
LINK rootptr1=NULL,rootptr2=NULL;
int x;
printf("Enter integers terminated \
with ctrl z\n");
/* Create tree */
while (scanf("%d",&x) == 1) {
add1(&rootptr1,x);
add2(&rootptr2,x);
}
printf("Using add1\n");
recurse_traverse(rootptr1); /* Traverse tree */
printf("Using add2\n");
recurse_traverse(rootptr2);
}
recurse_traverse(rootptr) LINK rootptr;
{
if (rootptr != NULL) { /* Is tree null? */
recurse_traverse(rootptr -> left); /* Recurse */
printf("%d\n",rootptr -> info);
recurse_traverse(rootptr -> right); /* Recurse */
}
}
add1(rootpp,val) LINK *rootpp;int val;
{
LINK newnode,current,previous;
/* Create a new node */
newnode = (LINK) malloc(sizeof(struct NODE));
newnode->info = val;
newnode->left = NULL;
newnode->right = NULL;
current = *rootpp;
previous = NULL;
while (current != NULL) { /* Search for leaf */
previous = current;
if (val < current->info)
current = current->left;
else
current = current->right;
}
if (previous == NULL) /* Null tree? */
*rootpp = newnode; /* Node becomes tree */
else
if (val < previous->info) /* Add left/right? */
previous->left = newnode; /* Add to left */
else
previous->right = newnode; /* Add to right */
}
add2(pp,val) LINK *pp; int val;
{
LINK newnode;
/* Create a new node */
newnode = (LINK) malloc(sizeof(struct NODE));
newnode->info = val;
newnode->left = NULL;
newnode->right = NULL;
while (*pp != NULL) { /* Search for leaf */
if (val < (*pp)->info)
pp = &(*pp)->left; /* Move pp */
else
pp = &(*pp)->right; /* Move pp */
}
*pp = newnode; /* Add node to tree */
}